package org.sxp.common.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.system.JavaRuntimeInfo;
import cn.hutool.system.JvmInfo;
import cn.hutool.system.RuntimeInfo;
import cn.hutool.system.SystemUtil;
import cn.hutool.system.oshi.CpuInfo;
import cn.hutool.system.oshi.OshiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
import org.sxp.common.utils.SslUtil;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.util.GlobalConfig;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

/**
 * @author shenxingping
 * @date 2021/05/10
 */
@Slf4j
@Component
public class ApplicationRunner implements org.springframework.boot.ApplicationRunner {

    @Value("${spring.application.name:}")
    private String appName;
    @Value("${server.port:}")
    private String port;
    @Value("${server.servlet.context-path:}")
    private String contextPath;

    /**
     * 全局忽略ssl请求校验授信主机名等问题
     */
    @PostConstruct
    public void init(){
        try{
            SslUtil.ignoreSsl();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private void runtimeInfo(){
        RuntimeInfo runtimeInfo = new RuntimeInfo();
        log.warn("JVM最大限制内存（Max Memory）：{}", FileUtil.readableFileSize(runtimeInfo.getMaxMemory()));
        log.warn("JVM已获得内存（Total Memory）：{}", FileUtil.readableFileSize(runtimeInfo.getTotalMemory()));
        log.warn("JVM已获得未使用内存（Free Memory）：{}", FileUtil.readableFileSize(runtimeInfo.getFreeMemory()));
        log.warn("JVM剩余可用内存（Usable Memory）：{}", FileUtil.readableFileSize(runtimeInfo.getUsableMemory()));
    }

    private void hostInfo(){
        long total = OshiUtil.getMemory().getTotal();
        log.warn("节点总内存：{}", FileUtil.readableFileSize(total));
        log.warn("节点可用内存：{}", FileUtil.readableFileSize(OshiUtil.getMemory().getAvailable()));
        log.warn("节点可用Cpu数量：{}", OshiUtil.getCpuInfo().getCpuNum());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        runtimeInfo();
        log.warn("---------------------------------------------");
        hostInfo();
        log.warn("当前SpringBoot【{}】服务已启动完成!!!端口【{}】，访问路径【{}】",appName, port, contextPath);
    }
}
